package de.reondo.jos;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

import org.jgrapht.Graph;

public class DependencyGraphPrinter<V, E> {

	private IGraphStyler<V, E> graphStyler;

	public DependencyGraphPrinter(IGraphStyler<V, E> graphStyler) {
		this.graphStyler = graphStyler;
	}
	
	public void writeAsDotFile(Graph<V, E> graph, String filename) throws IOException {
		PrintWriter w = new PrintWriter(filename, "UTF-8");

		w.println("digraph G {");
		w.println("node[shape=box,fontname=Helvetica,fontsize=10,colorscheme=blues9,style=filled]");
		w.println("edge[fontname=Helvetica,fontsize=10,colorscheme=dark27]");

		HashMap<V, String> vNames = new HashMap<V, String>();
		
		for (V vertex : graph.vertexSet()) {
		    String vName = vNames.get(vertex);
		    if (vName == null) {
		        vName = "N" + vNames.size();
		        vNames.put(vertex, vName);
		    }
		    w.println(vName + "[label=\""
					+ graphStyler.getVertexLabel(vertex) + "\",color="
					+ graphStyler.getColorForVertex(vertex) + "]");
		}
		for (E edge : graph.edgeSet()) {
			int colorIndex = Math.abs(edge.hashCode()) % 7 + 1; // index into color scheme dark27
            w.println(vNames.get(graph.getEdgeSource(edge)) + "->"
					+ vNames.get(graph.getEdgeTarget(edge))
					+ "[label=\"" + graphStyler.getEdgeLabel(edge) + "\",color="+colorIndex+",fontcolor="+colorIndex+"]");
		}
		w.println("}");
		w.close();
	}
	
	public void writeAsTgfFile(Graph<V, E> graph, String filename) throws IOException {
        PrintWriter w = new PrintWriter(filename, "UTF-8");
        
        HashMap<V, Integer> vNames = new HashMap<V, Integer>();
        for (V vertex : graph.vertexSet()) {
            Integer vName = vNames.get(vertex);
            if (vName == null) {
                vName = vNames.size();
                vNames.put(vertex, vName);
            }
            w.println(vName + " " + graphStyler.getVertexLabel(vertex));
        }
        w.println("#");
        for (E edge : graph.edgeSet()) {
            w.println(vNames.get(graph.getEdgeSource(edge)) + " " 
                    + vNames.get(graph.getEdgeTarget(edge)) + " "
                    + graphStyler.getEdgeLabel(edge));
        }
        w.close();
	}

}
